(function () {

	'use strict';

	angular
		.module('app')
		.controller('ConfirmCartController', ConfirmCartController);

	ConfirmCartController.$inject = ['$scope', '$http', '$location', '$state', '$rootScope', '$timeout', '$stateParams', 'API', 'ENUM', 'ConfirmCartService', 'ExpressSelectService', 'InvoiceSelectService', 'PaymentModel'];

	function ConfirmCartController($scope, $http, $location, $state, $rootScope, $timeout, $stateParams, API, ENUM, ConfirmCartService, ExpressSelectService, InvoiceSelectService, PaymentModel) {

		if (!ConfirmCartService.goods || !ConfirmCartService.goods.length) {
			$timeout(function () {
				$rootScope.goHome();
			}, 1);
			return;
		}

		$scope.touchAddress = function () {
            $state.go('address-select', {
                address_id: $scope.address ? $scope.address.address_id : null
            });
        };

        $scope.touchInvoice = function() {
            $scope.toast('暂不支持在线开票，请联系客服开具发票');
        };

		$scope.touchExpress = function () {
            if (!$scope.address) {
                $scope.toast('请选择地址');
                return;
            }

            var goods = $scope.goods;
            var goodsIds = [];
            var numbers = [];

            for (var i = 0; i < goods.length; ++i) {
                goodsIds.push(goods[i].goods_id);
                numbers.push(goods[i].num);
            }

            ExpressSelectService.clear();
            ExpressSelectService.expressId = $scope.express ? $scope.express.express_id : null;
            ExpressSelectService.goodsIds = goodsIds;
            ExpressSelectService.goodsNumbers = numbers;
            ExpressSelectService.address_id = $scope.address.address_id;

            $state.go('express-select', {});
        };

		$scope.touchSubmit = _touchSubmit;

		$scope.refreshComment = function (){
            ConfirmCartService.input.comment = $scope.input.comment;
        };

        $scope.addList = [];
		$scope.goods = ConfirmCartService.goods;
		$scope.address = ConfirmCartService.address;
		$scope.express = ConfirmCartService.express;
		$scope.all_discount = 0;
		$scope.express_count = 0;
        $scope.input = {
			comment: ""
		};

		$scope.input.comment = ConfirmCartService.input.comment;

		$scope.priceInfo = null;

        $scope.canPurchase = function () {
            if (!$scope.goods || !$scope.goods.length)
                return false;
            if (!$scope.address)
                return false;
            if (!$scope.express)
                return false;

            return true;
        };

		function _touchSubmit() {
			var cart_ids = [];
			var goods = $scope.goods;
			var address = $scope.address;
			var express = $scope.express;
			var comment = $scope.input.comment;
			var is_real = 0;

			if (!goods || !goods.length) {
				$scope.toast('商品信息不存在');
				return;
			}

			if (!address) {
				$scope.toast('请填写地址');
				return;
			}

            for (var i = 0; i < goods.length; ++i) {
				if (goods[i].is_real==1) {
                    is_real = 1;
				}
                if (goods[i].cart_id) {
                    cart_ids.push(goods[i].cart_id);
				}
            }
            if (!$scope.express && is_real) {
                $scope.toast('请选择快递');
                return;
			}

			var params = {
                cart_ids: JSON.stringify(cart_ids),
                address_id: address ? address.address_id : null,
                express_region_id: express ? express.express_region_id : null,
                leave_words: comment
			};
			API.cart.checkoutCart(params).then(function (res) {
				if (res) {
					ConfirmCartService.clear();
					ExpressSelectService.clear();
					PaymentModel.clear();
					$state.go('payment', {
						order_id: res.order_id
					});
				}
			});
		}

		function _reloadAddress() {
			API.consignee.getAddList({}).then(function (res) {
				if (res) {
					$scope.addList = res;
					if (!$scope.address) {
						for (var key in $scope.addList) {
							if ($scope.addList[key].is_default) {
								$scope.address = $scope.addList[key];
								$rootScope.$emit('consigneeChanged', $scope.address);
							}
						}
					}
				}
				_reloadExpress();
            })
        }

		function _reloadPrice() {
			var goods = $scope.goods;
			var express = $scope.express;

			if (!goods || !goods.length) {
				$scope.toast('商品信息不存在');
				return;
			}

			var products = [];
			for (var i = 0; i < goods.length; ++i) {
				products.push({
					goods_id: goods[i].goods_id,
					num: goods[i].num
				});
			}

			var params = {};
			params.order_goods = JSON.stringify(products);
			if (express) {
				params.express_region_id = express.express_region_id;
			}

			API.order.getCheckPrice(params).then(function (res) {
				$scope.priceInfo = res;
				$scope.all_discount = res.discount_price;
			});
		}

		function _reloadExpress() {
			//1、需要开发票的时候 获取配送方式
			//2、有实物商品时 获取配送方式
			var is_real=0;
            for (var x in $scope.goods ){
            	if($scope.goods[x].is_real == 1){
                    is_real = 1;
                    $scope.express_count += 1;
				}
			}

            if (!$scope.express && is_real) {
				var goods = [];
                var allgoods = $scope.goods;

                for (var i = 0; i < allgoods.length; ++i) {
                    goods.push({
                        goods_id: allgoods[i].goods_id,
                        num: allgoods[i].num
                    })
                }

                API.shipping.getFirstExpress({
                    goods: JSON.stringify(goods),
                    address_id: $scope.address.address_id
                }).then(function (res) {
					$scope.express = res;
					_reloadPrice();
				});
            }
        }

		function _reload() {
			_reloadPrice();
			_reloadAddress();
		}

		_reload();
	}

})();